<?php
/**
 * Created by PhpStorm.
 * User: function
 * Date: 2018-04-13
 * Time: 2:04
 */

namespace app\api\controller\v1;

use app\common\logic\InfoLogic;
use app\common\controller\Api;
use app\common\model\InfoData;
use app\common\model\InfoPic;
use app\common\model\Info as InfoModel;
use app\common\logic\CommentLogic;
use app\common\model\InfoAgree;
use think\Log;

class Info extends Api
{
    protected $authenticate = ['except' => 'index,read'];
    
    protected $add_rule = [
        'user_id|用户id' => 'require',
        'title|标题' => 'require',
        'content|内容' => 'require',
        'catid|分类' => 'require'
    ];
    
    public function index()
    {
        $params = paramForm();
        
        //各种订单的操作，下单之类的
        if (isset($params['action'])) {
            switch ($params['action']) {
                case 'add':
                    $this->save($params);
                    break;
                case 'my':
                    $this->my($params);
                    break;
                case 'del':
                    $this->del($params);
                    break;
                case 'change':
                    $this->update($params);
                    break;
                case 'addComment':
                    $this->addComment($params);
                case 'agree':
                    $this->agree($params);
                    break;
                case 'comment':
                    $this->comment($params);
                    break;
                default:
                    
                    break;
            }
        }
        
        parent::index();
        
        
    }
    
    public function del($params){
        if(!isset($params['id'])){
            error('id必传');
        }
        $info = InfoModel::get($params['id']);
        if(!$info||$info->user_id!=$this->getUserId()){
            error('指定资源不存在或者没有权限删除');
        }
        $info->delete();
        success(null);
    }
    
    public function my($params)
    {
        
        $params['user_id'] = $this->getUserId();
        $logicClass = $this->logicClass;
        $logic = new $logicClass();
        
        $lists = $logic->getList($params);
        if ($lists) {
            success($lists);
        } else {
            error('没有符合的数据');
        }
        
        
    }
    
    public function read($params)
    {
        
        $logicClass = $this->logicClass;
        $logic = new $logicClass();
        
        $logic->setSql($params);
        $one = $logic->findModel();
        
        $agreeList = InfoAgree::all(['info_id' => $one['id']]);
        $one['agreeCount'] = count($agreeList);
        
        if ($one) {
            success($one);
        } else {
            error('数据不存在或者无权限查看');
        }
        
    }
    
    
    public function agree($params)
    {
        $rule = ['id|资讯id' => 'require', 'user_id|用户id' => 'require'];
        $logic = new InfoLogic();
        $info = $logic->findModel($params['id']);
        $userId = $this->getUserId();
        $params['user_id'] = $userId;
        
        $this->validate($params, $rule);
        
        $has = InfoAgree::get(['info_id' => $params['id'], 'user_id' => $userId]);
        if ($has) {
            error('已经点过赞了');
        }
        
        $agree = new InfoAgree(['info_id' => $params['id'], 'user_id' => $userId]);
        $agree->save();
        success($agree->id);
        
    }
    
    public function save($params)
    {
        
        $user = $this->getUserInfo();
        $params['user_id'] = $user->id;
        $params['username'] = $user->nickname;
        $this->validate($params, $this->add_rule);
        $logic = new InfoLogic();
        
        $infoId = $logic->add($params);
        
        if (!$infoId) {
            return callerror('新增失败');
        }
        
        $con = new InfoData(['info_id' => $infoId, 'content' => $params['content']]);
        $con->save();
        
        $pics = $params['pics'];
        $wxDevConfig = config('thirdaccount.WeChatDeveloper');
        try {
            $picArr = [];
            $picModel = new InfoPic();
            $wechat = new \WeChat\Media($wxDevConfig);
            $wechat->delAccessToken();
            foreach ($pics as $pic) {
                
                // 实例接口
                
                // 保存到本地
                $result = $wechat->get($pic);
                
                // 处理执行的结果
                if ($result === FALSE) {
                    // 接口失败的处理
                    error('获取微信临时文件资源失败');
                } else {
                    $filename = uniqid() . '.jpg';            //定义图片名字及格式
                    $tempFile = saveFile($filename, $result);
                    $file = new \think\File($tempFile);
                    
                    if ($file) {
                        $file->setUploadInfo(['name' => $filename]);
                        
                        $oss_url = $this->uploadToAlyun($file);
                        $picArr[] = ['info_id' => $infoId, 'url' => $oss_url];
                    } else {
                        error('上传文件缺失');
                    }
                    
                }
            }
            
            
            $picModel->saveAll($picArr);
            
        } catch (Exception $e) {
            // 出错啦，处理下吧
            echo error($e->getMessage());
            
        }
        success('发布成功');
    }
    
    public function addComment($params)
    {
        $rule = [
            'id|资讯id' => 'require',
            'user_id|评论人' => 'require',
            'content|评论内容' => 'require'
        ];
        $params = paramForm();
        $params['user_id'] = $this->getUserId();
        $this->validate($params, $rule);
        
        $logic = new InfoLogic();
        $rt = $logic->addComment($params);
        
        if (!$rt['code']) {
            error('评论失败');
        }
        
        success($rt['data']);
    }
    
    public function comment($params)
    {
        
        $commentLogic = new CommentLogic();
        $commentLogic->setSql($params);
        $lists = $commentLogic->prepareDataProvider();
        
        success($lists);
    }
    
    
}